<template>
  <div>
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="奈雪的茶"
      left-arrow
      right-text="登录"
      @click-left="onClickLeft"
      @click-right="onClickRight"
    />
    <van-form>
      <van-field
        v-model="usercode"
        name="用户名"
        label="用户名"
        @blur.native.capture="checkName"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        @blur.native.capture="checkPwd"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" @click="checkForm"
          >立即注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      usercode: "",
      password: "",
    };
  },
  methods: {
    onClickLeft() {
      this.$router.push({ name: "Home" });
    },
    onClickRight() {
      this.$router.push({ name: "Login" });
    },

    /** 验证用户名 */
    checkName() {
      let exp = /^\w{6,15}$/;
      if (exp.test(this.usercode)) {
        // 验证成功
        this.nameState = "success";
        return true;
      } else {
        // 验证失败
        this.nameState = "error";
        return false;
      }
    },

    /** 验证密码框 */
    checkPwd() {
      let exp = /^\d{6}$/;
      if (exp.test(this.password)) {
        this.pwdState = "success";
        return true;
      } else {
        this.pwdState = "error";
        return false;
      }
    },

    /** 验证表单 */
    checkForm() {
      console.log("验证成功，开始发送注册请求...");
      // 发送注册请求
      this.axios
        .post(
          "http://172.88.22.18:3000/mumber/register",
          `usercode=${this.usercode}&password=${this.password}`
        )
        .then((res) => {
          console.log("注册业务", res);
          if (res.data.code == 200) {
            this.$toast("注册成功");
            this.$router.push("/login");
          } else if (res.data.code == 201) {
            // 用户已存在
            this.$messagebox({
              title: "提示",
              message: "账号已存在，请重新输入",
            });
          }
        })
        .catch((err) => {
          console.error("注册失败", err);
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
